<template>
  <div id="app">
    <h2>第九个练习</h2>
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add()">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, i) in arr" :key="item.id">
          <td>{{ i + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      uname: "",
      age: "",
      sex: "男",
      flag: "",
      arr: [
        {
          id: 0,
          uname: "Tom",
          age: 23,
          sex: "女",
        },
        {
          id: 1,
          uname: "Jone",
          age: 13,
          sex: "男",
        },
        {
          id: 2,
          uname: "Jane",
          age: 26,
          sex: "女",
        },
      ],
    };
  },
  methods: {
    // 新增功能
    add() {
      if (this.uname.length === 0 || this.age.length === 0) {
        return alert("请输入新增内容");
      }

      if (this.flag === "") {
        // 添加数据
        this.arr.push({
          id: +new Date(),
          uname: this.uname,
          age: this.age,
          sex: this.sex,
        });
      } else {
        this.flag.uname = this.uname;
        this.flag.age = this.age;
        this.flag.sex = this.sex;
      }

      // 清空
      this.uname = "";
      this.age = "";
      this.sex = "男";

      //重置flag
      this.flag = "";
    },

    // 编辑功能
    edit(id) {
      const obj = this.arr.find((item) => item.id === id);
      // 点击编辑给flag重新赋值
      this.flag = obj;
      const { uname, age, sex } = obj;
      this.uname = uname;
      this.age = age;
      this.sex = sex;
    },

    // 删除功能
    del(id) {
      this.arr = this.arr.filter((item) => item.id !== id);
    },
  },
};
</script>
